import React, { useState, useEffect } from 'react';
import { Drawer, Table, Tag, Empty, Spin, Descriptions, message } from 'antd';
import { LinkOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { DubboProviderDTO, DubboReferenceDetailDTO, ConsumerUnit, getReferencedBy } from '../../../../services/dubboAnalysis';
import type { ColumnsType } from 'antd/es/table';

interface ReferenceDetailDrawerProps {
    visible: boolean;
    provider: DubboProviderDTO | null;
    onClose: () => void;
}

const ReferenceDetailDrawer: React.FC<ReferenceDetailDrawerProps> = ({ visible, provider, onClose }) => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState<boolean>(false);
    const [referenceDetail, setReferenceDetail] = useState<DubboReferenceDetailDTO | null>(null);

    // 加载引用详情数据
    const loadReferenceDetail = async (configId: number) => {
        setLoading(true);
        try {
            const data = await getReferencedBy(configId);
            setReferenceDetail(data);
        } catch (error: any) {
            message.error(error.message || '加载引用详情失败');
            setReferenceDetail(null);
        } finally {
            setLoading(false);
        }
    };

    // 当抽屉打开且有 provider 时加载数据
    useEffect(() => {
        if (visible && provider) {
            loadReferenceDetail(provider.configId);
        } else {
            setReferenceDetail(null);
        }
    }, [visible, provider]);

    // 处理单元名称点击，跳转到单元详情页面
    const handleUnitClick = (unitId: string) => {
        navigate(`/unit/${unitId}/dubbo`);
        onClose(); // 关闭抽屉
    };

    // 表格列定义
    const columns: ColumnsType<ConsumerUnit> = [
        {
            title: '单元名称',
            dataIndex: 'unitName',
            key: 'unitName',
            width: 200,
            render: (text: string, record: ConsumerUnit) => (
                <a
                    onClick={() => handleUnitClick(record.unitId)}
                    style={{
                        color: '#1890ff',
                        cursor: 'pointer',
                        fontWeight: 500,
                        display: 'flex',
                        alignItems: 'center',
                        gap: '4px'
                    }}
                >
                    <LinkOutlined style={{ fontSize: '12px' }} />
                    {text}
                </a>
            ),
        },
        {
            title: '应用名称',
            dataIndex: 'appName',
            key: 'appName',
            width: 200,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '消费版本',
            dataIndex: 'consumerVersion',
            key: 'consumerVersion',
            width: 120,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
    ];

    return (
        <Drawer
            title={
                <div style={{ fontSize: '18px', fontWeight: 600 }}>
                    服务引用详情
                </div>
            }
            placement="right"
            width={800}
            open={visible}
            onClose={onClose}
            destroyOnClose
        >
            {loading ? (
                <div style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: '300px'
                }}>
                    <Spin size="large" tip="加载中..." />
                </div>
            ) : referenceDetail ? (
                <>
                    {/* 接口基本信息 */}
                    <div style={{
                        background: '#f5f5f5',
                        padding: '16px',
                        borderRadius: '8px',
                        marginBottom: '24px'
                    }}>
                        <div style={{
                            fontSize: '16px',
                            fontWeight: 600,
                            color: '#333',
                            marginBottom: '16px'
                        }}>
                            接口信息
                        </div>
                        <Descriptions column={1} size="small">
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>接口全限定名</span>}
                            >
                                <span style={{ color: '#1890ff', fontFamily: 'monospace' }}>
                                    {referenceDetail.interfaceFqn}
                                </span>
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>服务分组</span>}
                            >
                                {referenceDetail.serviceGroup ? (
                                    <Tag color="blue">{referenceDetail.serviceGroup}</Tag>
                                ) : (
                                    <span style={{ color: '#999' }}>-</span>
                                )}
                            </Descriptions.Item>
                            <Descriptions.Item
                                label={<span style={{ fontWeight: 500 }}>版本号</span>}
                            >
                                {referenceDetail.version ? (
                                    <Tag color="green">{referenceDetail.version}</Tag>
                                ) : (
                                    <span style={{ color: '#999' }}>-</span>
                                )}
                            </Descriptions.Item>
                        </Descriptions>
                    </div>

                    {/* 引用者列表 */}
                    <div>
                        <div style={{
                            fontSize: '16px',
                            fontWeight: 600,
                            color: '#333',
                            marginBottom: '16px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between'
                        }}>
                            <span>引用者列表</span>
                            <Tag color="orange" style={{ fontSize: '14px', padding: '4px 12px' }}>
                                共 {referenceDetail.consumers.length} 个单元引用
                            </Tag>
                        </div>

                        {referenceDetail.consumers.length > 0 ? (
                            <Table
                                columns={columns}
                                dataSource={referenceDetail.consumers}
                                rowKey="unitId"
                                pagination={false}
                                size="middle"
                                locale={{
                                    emptyText: (
                                        <Empty
                                            description={
                                                <span style={{ color: '#999' }}>
                                                    暂无单元引用此服务
                                                </span>
                                            }
                                        />
                                    ),
                                }}
                                style={{
                                    background: '#fff',
                                    borderRadius: '8px',
                                    border: '1px solid #f0f0f0'
                                }}
                            />
                        ) : (
                            <Empty
                                description={
                                    <div style={{ padding: '40px 0' }}>
                                        <div style={{ fontSize: '16px', color: '#999', marginBottom: '8px' }}>
                                            暂无单元引用此服务
                                        </div>
                                        <div style={{ fontSize: '14px', color: '#bfbfbf' }}>
                                            该服务目前没有被其他单元消费
                                        </div>
                                    </div>
                                }
                            />
                        )}
                    </div>
                </>
            ) : (
                <Empty
                    description={
                        <span style={{ color: '#999' }}>
                            暂无数据
                        </span>
                    }
                />
            )}
        </Drawer>
    );
};

export default ReferenceDetailDrawer;
